package battleship.cxbr;

import battleship.emss.Context;
import battleship.emss.CxBRAgent;
import battleship.emss.Fire;
import battleship.emss.Move;
import battleship.emss.Status;
import battleship.emss.physics;

public class EvadeContext extends Context {
	
	private double direction = 0;
	double enemyDistance = 0;
	double EVADE_DISTANCE = 20000.0;
	int x = 0, y = 0;
	int neg = -1;
	boolean mutex = false;
	
	
	public EvadeContext(String n, CxBRAgent a) {
		super(n, a);
		// TODO Auto-generated constructor stub
	}

	public void Initialize(double arg0) {
		// TODO Auto-generated method stub
		
	}
	
	@Override
	public void Action(double arg0) {
		neg = 1;

		Agent.actions.clear();
		
		for (int i = 0; i < Agent.detectedStatus.size(); i++){
			
			Status tmpStatus = Agent.detectedStatus.get(i);
			
			if( tmpStatus.team != Agent.status.team && 
				tmpStatus.type == Agent.TORPEDO){
				double distance = Evaluate.distance(Agent.status, tmpStatus);
				if (tmpStatus.alive == 1 && distance < EVADE_DISTANCE){  // Nuclear launch detected
					Agent.actions.clear();
					Agent.status.status = " Can't touch this!";
					direction = Math.atan2((Agent.status.my - tmpStatus.my),(Agent.status.mx - tmpStatus.mx));
					//if (Agent.status.torpedos % 1 == 0){ neg = -1; }
					double offset = Math.min(Math.PI/2, Math.PI * 1000 / distance);
					//System.out.println("Theta: " + offset * 180 / Math.PI);
					Agent.actions.add(new Move(direction + offset, 15));
					break;
				}
			}
		}
	}

	@Override
	public double ParentRule(double arg0) {
		//if (x++ % 1000 == 0)
		//	System.out.println("Evade - Parent Rule");
		for(int i = 0; i < Agent.detectedStatus.size(); i++){
			
			Status tmpStatus = Agent.detectedStatus.get(i);
			
			if(	tmpStatus.team != Agent.status.team && 
				tmpStatus.type == Agent.TORPEDO &&
				tmpStatus.alive == 1 && 
				Evaluate.distance(Agent.status, tmpStatus) < EVADE_DISTANCE){
				return 1.0;
			}
		}
		
		return 0.0d;
	}

	@Override
	public double SiblingRule(double arg0) {
		//if (y++ % 1000 == 0)
		//System.out.println("Evade - Sibling Rule");
		for(int i = 0; i < Agent.detectedStatus.size(); i++){
			
			Status tmpStatus = Agent.detectedStatus.get(i);
			
			if(	tmpStatus.team != Agent.status.team && 
				tmpStatus.type == Agent.TORPEDO &&
				tmpStatus.alive == 1 &&
				Evaluate.distance(Agent.status, tmpStatus) < 10000){
				return 1.0;
			}
		}
		
		return 0.0d;
	}

}
